# -*- coding: utf-8 -*-
import random
import scrapy
from scrapy import Request
from scrapy.utils.project import get_project_settings
from scrapy.exceptions import IgnoreRequest
from zc_core.util.http_util import retry_request
from zc_core.dao.sku_pool_dao import SkuPoolDao
from zc_core.dao.batch_dao import BatchDao
from zc_core.util.done_filter import DoneFilter
from guangdong.rules import *
from zc_core.spiders.base import BaseSpider


class FullSpider(BaseSpider):
    name = 'full'
    # 常用链接
    item_url = 'http://210.76.73.186/commodities/{}?p_id={}'

    def __init__(self, batchNo=None, *args, **kwargs):
        super(FullSpider, self).__init__(batchNo=batchNo, *args, **kwargs)
        # 创建批次记录
        BatchDao().create_batch(self.batch_no)
        # 避免重复采集
        self.done_filter = DoneFilter(self.batch_no)

    def start_requests(self):
        settings = get_project_settings()
        pool_list = SkuPoolDao().get_sku_pool_list()
        self.logger.info('全量: %s' % (len(pool_list)))
        random.shuffle(pool_list)
        for sku in pool_list:
            sku_id = sku.get('_id')
            spu_id = sku.get('spuId')
            sp_code = sku.get('supplierCode')
            sold_count = sku.get('soldCount')
            # 避免无效采集
            if self.done_filter.contains(sku_id) and not settings.get('FORCE_RECOVER', False):
                self.logger.info('已采: %s', sku_id)
                continue
            # 采集商品关联关系
            yield Request(
                url=self.item_url.format(spu_id, sku_id),
                callback=self.parse_item_data,
                errback=self.error_back,
                meta={
                    'reqType': 'item',
                    'batchNo': self.batch_no,
                    'skuId': sku_id,
                    'spuId': spu_id,
                    'supplierCode': sp_code,
                    'soldCount': sold_count,
                },
            )

    # 处理ItemData
    def parse_item_data(self, response):
        meta = response.meta
        data = parse_item_data(response)
        if data:
            self.logger.info('商品: [%s]' % data.get('skuId'))
            yield data
        else:
            self.logger.info('下架: %s' % meta.get('url'))
